/** Copyright 2014, Ross Mahony. Some rights reserved. See COPYING. */
package models

import play.api.db.slick.Config.driver.simple._
import scala.slick.lifted.Tag

case class Customer(id: Option[Long], 
	name: String, lastName: String, telephone: String, 
	email: String, address: String, city: String, county: String, 
	postcode: String)

/** Customer entity. */
class CustomerTbl(tag: Tag) extends Table[Customer](tag, "CUST") {

  def id = column[Long]("ID", O.PrimaryKey, O.AutoInc)
  def name = column[String]("NAME", O.NotNull)
  def lastName = column[String]("SURNAME", O.Nullable)
  def telephone = column[String]("TEL", O.Nullable)
  def email = column[String]("EMAIL", O.Nullable)
  def address = column[String]("ADDR", O.NotNull)
  def city = column[String]("CITY", O.NotNull)
  def county = column[String]("COUNTY", O.NotNull)
  def postcode = column[String]("POSTCODE", O.NotNull)
  def * = (id.?, name, lastName, telephone, email, 
  	address, city, county, postcode) <> (Customer.tupled, Customer.unapply _)
}

/** Customer DAO */
object CustomerDAO {
  val customers = TableQuery[CustomerTbl]
  
 /**
	* Retrieve a [[models.Customer]] by the id
  *
	* @param id Customer ID
	*/
	def findById(id: Long)(implicit s: Session): Option[Customer] =
	customers.where(_.id === id).firstOption

 /** Fetch all customers */ 
  def list(implicit s: Session) = {
     customers.sortBy(_.name).list
  }

 /**
  * Retrieve a [[models.Customer]] by the id or fetch the first record
  * if None option was passed
  *
  * @param id Customer ID or None if wanting to fetch the first record
  */
  def loadCustomer(id: Option[Long])(implicit s: Session) = { 
      id match {
        case None => customers.firstOption
        case Some(id: Long) => findById(id)
      }
  }

 /** Count all customers */
  def count(implicit s: Session): Int = Query(customers.length).first

 /**
  * Insert a new [[models.Customer]]
  *
  * @param customer [[models.Customer]] case class to insert 
  */
  def insert(customer: Customer)(implicit s: Session) {
    customers.insert(customer)
  }

 /**
  * Insert a new [[models.Customer]] by ignoring auto inc column
  *
  * @param customer [[models.Customer]] case class to insert 
  */
  def forceInsert(customer: Customer)(implicit s: Session) {
    customers.forceInsert(customer)
  }


 /** Delete all customers */
  def deleteAll(implicit s: Session) {
    customers.delete
  }

}
